package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.common.ThreadCommon;
import com.itheima.pojo.*;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    OrdersService ordersService;

    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    UserService userService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    OrderDetailService orderDetailService;

    @Value("${import.pathOut}")
    private String pathOut;

    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders) {
        Long tableLogic = ThreadCommon.getTableLogic();
        //用户下单id
        orders.setUserId(tableLogic);
        //用户下单时间
        orders.setOrderTime(LocalDateTime.now());
        //用户结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //创建订单编号
        long id = IdWorker.getId();
        //订单编号
        orders.setNumber(String.valueOf(id));
        //实收金额 获取购物车的数据 价格*数量
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ShoppingCart::getUserId, tableLogic);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);

        /*BigDecimal decimal = new BigDecimal(0);

        //BigDecimal add=null;
        for (ShoppingCart shoppingCart : list) {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, detail);

            detail.setOrderId(id);

            BigDecimal decimal1 = new BigDecimal(shoppingCart.getNumber());
            BigDecimal decimal2 = shoppingCart.getAmount();
            detail.setAmount(decimal1.multiply(decimal2));
            orderDetailService.save(detail);
            decimal.add(detail.getAmount());
            log.info("----------------------------------");
            log.info(detail.getAmount().toString());

        }*/
        //AtomicInteger atomicInteger = new AtomicInteger(0);
        BigDecimal amount = new BigDecimal(0);//总价
        // 4、保存订单明细数据：点了哪些菜品或套餐
        for (ShoppingCart shoppingCart : list) {
            // ShoppingCart shoppingCart --> OrderDetail orderDetail
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            // orderId单独设置
            orderDetail.setOrderId(id);
            // amount 金额单独设置 数量  *  单价
            BigDecimal price = shoppingCart.getAmount();//价格
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());//数量
            BigDecimal multiply = price.multiply(number);
            /*BigDecimal add = amount.add(multiply);
            amount=add;*/
            //将餐品单价*个数的总价存入orderDetail中
            orderDetail.setAmount(price.multiply(number));
            //amount=amount.add(orderDetail.getAmount());
            amount=amount.add(multiply);
            //餐品总价日志信息
            //atomicInteger.addAndGet(price.multiply(number).intValue());
            orderDetailService.save(orderDetail);
        }
        orders.setAmount(amount);
        //orders.setAmount(new BigDecimal(atomicInteger.get()));
        //用户名
        User user = userService.getById(tableLogic);
        String name = user.getName();
        orders.setUserName(name);
        //手机号
        orders.setPhone(user.getPhone());
        //地址
        AddressBook book = addressBookService.getById(orders.getAddressBookId());
        orders.setAddress(book.getDetail());
        //收货人
        orders.setConsignee(book.getConsignee());
        ordersService.save(orders);
        //清空购物车
        QueryWrapper<ShoppingCart> wrapper1 = new QueryWrapper<>();
        wrapper1.lambda().eq(ShoppingCart::getUserId,tableLogic);
        shoppingCartService.remove(wrapper1);
        return R.success(orders);
    }

    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, Long number,String beginTime,String endTime) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.lambda().like(number!=null,Orders::getId,number);
        wrapper.lambda().between(beginTime!=null&&endTime!=null,Orders::getOrderTime,beginTime,endTime);
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        ordersService.page(ordersPage,wrapper);
        return R.success(ordersPage);
    }
    @GetMapping("/userPage")
    public R page(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        ordersService.page(ordersPage);
        return R.success(ordersPage);
    }


    @GetMapping("/orderOut")
    public R orderOut() {
        List<Orders> list = ordersService.list();
        String outName = pathOut+"瑞吉订单"+System.currentTimeMillis()+".xlsx";
        EasyExcel.write(outName, Orders.class).sheet("瑞吉订单").doWrite(list);
        return R.success("导出成功");
    }
}
